<template>
	<notice :notice.sync="notice"></notice>
    <header-paper action="testPaper" :cla-id="paper.class_cla_id"></header-paper>
    
    <div class="loading" v-show="loading">
        <i class="fa fa-spinner fa-spin fa-3x"></i>
    </div>

    <div class="container" data-spy="scroll" data-target="#scrollspy" id="question-container" v-show="!loading">
        <div class="row">
            <div class="col-md-4 col-md-offset-2">
                <span class="quiz-name">{{ paper.qus_name }}</span> 
                <span class="text-muted">{{ paper.qus_create_time }}</span>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 col-md-offset-2">
                <button class="btn btn-primary" v-on:click="chagePaperStatus()" v-if="paper.qus_status == 0">开始测试</button>
                <button class="btn btn-default" v-on:click="chagePaperStatus()" v-if="paper.qus_status == 1">结束测试</button>
                <button class="btn btn-default" v-on:click="chagePaperStatus()" v-if="paper.qus_status == 2">继续测试</button>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-2" id="scrollspy">
                <ul class="nav nav-tabs nav-stacked" data-spy="affix" data-offset-top="180">
                    <li>选择试题类型</li>
                    <template v-for="item in TYPETEXT">
                        <li><button class="btn btn-link" v-on:click="appendQue($index)">{{ item }}</button></li>
                    </template>
                </ul>
            </div>
            <div class="col-sm-9">
                <ul class="sortable-list">
                    <li v-for="que in ques" >
                        <paper-item :que="que"
                                    :index="$index"
                                    @msg="showMsg"
                                    @del-que="beforeDelQue($index)"
                                    @cancel-edit="cancelEdit($index)"
                                    @save-que="saveQue($index)">
                        </paper-item>
                    </li>
                </ul>
                
            </div>
        </div>
    </div>

    <modal type="modal-sm" id="del-que">
        <h4 slot="header" class="modal-title text-danger">删除题目</h4>
        <p slot="body">确定删除题目 <span class="text-info">{{ques[delIndex]&&ques[delIndex].que_num}}</span> 吗</p>
        <button slot="footer" type="button" class="btn btn-danger" @click="delQue()">删除</button>
    </modal>

</template>

<script>
	import HeaderPaper from '../../Component/HeaderPaper/HeaderPaper';
    import Notice from '../../Component/Notice/Notice';
    import PaperItem from '../../Component/PaperItem/PaperItem';
    import Modal from '../../Component/Modal/Modal';
    import Sortable from 'sortablejs';


    export default {
        created: function() {
            this.getPaper();
            this.getPaperInfo();
        },
        ready: function() {
            var vm = this;
            Sortable.create(document.getElementsByClassName('sortable-list')[0], {
                animation: 250,
                handle: '.handle',
                filter: '.ignore-elements',
                onUpdate: function(event) {
                    console.log(event.oldIndex, event.newIndex);
                    vm.$http.post('/question/move', 
                        {que_id1: vm.ques[event.oldIndex].que_id, que_id2: vm.ques[event.newIndex].que_id}).then(function(resp) {
                            if (resp.data.status === 1) {
                                vm.notice = {type: 1, msg: "移动成功"};
                            } else {
                                vm.notice = {type: 0, msg: resp.data.message};
                            }
                    }, function(resp) {
                        // error callback
                        vm.notice = {type: 0, msg: resp.statusText};
                    })
                    vm.ques.splice(event.newIndex, 0, vm.ques.splice(event.oldIndex, 1)[0]);
                    vm.ques.forEach((item, index) => {
                        item.que_num = index+1;
                    })
                    console.log(vm.ques)
                }
            })
        },
        data() {
            return {
                tpId: location.search.slice(1).split('=')[1],
                notice: {type: 0, msg: ""},
                loading: false,
                paper: {},
                ques: [],
                delIndex: -1,
                TYPETEXT : ["判断题", "单选题", "多选题", "填空题", "简答题"]
            }
        },
    	components: {
    		HeaderPaper,
    		Notice,
            PaperItem,
            Modal
    	},
        methods: {
            getPaper: function() {
                this.loading = true;
                this.$http.post('/question/question', {qus_id: this.tpId}).then(function(resp) {
                    this.loading = false;
                    if (resp.data.status === 1) {
                        var ques = resp.data.data;

                        ques.forEach((value) => {
                            value.editing = false;
                            // 将选项保存到数组
                            value.que_items = [];
                            for (let i = 1; i <= 8; i++) {
                                if (value["que_item"+i]) {
                                    value.que_items.push(value["que_item"+i]);
                                }
                                delete value["que_item"+i];
                            }
                            if (value.que_type == 2) {
                                value.que_answer = value.que_answer.split("");
                            }
                            // 备份题目中能修改的项
                            value.contentBak = value.que_content;
                            value.scoreBak = value.que_score;
                            value.itemsBak = value.que_items.concat();
                            value.answerBak = value.que_type==2?value.que_answer.concat():value.que_answer;
                        })
                        this.ques = ques;

                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                }, function(resp) {
                    // error callback
                    this.loading = false;
                    this.notice = {type: 0, msg: resp.statusText};
                })
            },
            getPaperInfo: function() {
                this.$http.post('/questionSet/getQuizInfo', {qus_id: this.tpId}).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.paper = resp.data.data;
                    }
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
            },
            showMsg: function(msg, type) {
                this.notice = {type: type, msg: msg};
            },
            beforeDelQue: function(index) {
                this.delIndex = index;
                $('#del-que').modal('toggle');
            },
            delQue: function() {
                var postData = {
                    qus_id: this.paper.qus_id, 
                    que_id: this.ques[this.delIndex].que_id
                };
                this.$http.post('/question/delete', postData).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.notice = {type: 1, msg: resp.data.message};
                        // 备份
                        for (let i = this.delIndex+1; i < this.ques.length; i++)
                            this.ques[i].que_num--;
                        this.ques.splice(this.delIndex, 1);
                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
                $('#del-que').modal('toggle');
            },
            appendQue: function(index) {
                var que = {
                    que_type: index,
                    que_content: '',
                    que_num: this.ques.length+1,
                    que_items: [],
                    que_score: '',
                    que_answer: '',
                    editing: true
                }
                if (index === 0) {
                    que.que_items = ['对', '错'];
                    que.que_answer = -1;
                } else if (index === 1) {
                    que.que_items = ['','','',''];
                    que.que_answer = -1;
                }  else if (index === 2) {
                    que.que_items = ['','','',''];
                    que.que_answer = [];
                } else if (index === 3 || index === 4) {
                    que.que_answer = '';
                }
                this.$broadcast('append-que');
                this.ques.push(que);
                $('html,body').animate({scrollTop:document.body.scrollHeight});
            },
            cancelEdit: function(index) {
                var que = this.ques[index];
                if (que.que_id) {
                    que.editing = false;
                    que.que_content = que.contentBak;
                    que.que_score = que.scoreBak;
                    que.que_items = que.itemsBak.concat();
                    que.que_answer = que.que_type==2?que.answerBak.concat():que.answerBak;
                } else {
                    for (let i = index+1; i < this.ques.length; i++)
                        this.ques[i].que_num--;
                    this.ques.splice(index, 1);
                }
            },
            saveQue: function(index) {
                var postData = {},
                    que = this.ques[index],
                    postUrl = que.que_id? '/question/update' : '/question/add';
                // 选项
                if (que.que_type < 3) {
                    que.que_items.forEach((value, index) => {
                        postData['que_item'+(index+1)] = value;
                    })
                }
                // 答案
                if (que.que_type == 2) {
                    postData['que_answer'] = que.que_answer.join("");
                } else {
                    postData['que_answer'] = que.que_answer;
                }
                // 其他
                postData['que_type'] = que.que_type;
                postData['que_score'] = que.que_score;
                postData['que_content'] = que.que_content;
                postData['que_id'] = que.que_id;
                postData['qus_id'] = this.paper.qus_id;

                this.$http.post(postUrl, postData).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.notice = {type: 1, msg: resp.data.message};
                        if (!que.que_id) que.que_id = resp.data.data;
                        // 备份
                        que.contentBak = que.que_content;
                        que.scoreBak = que.que_score;
                        que.itemsBak = que.que_items.concat();
                        que.answerBak = que.que_type==2?que.que_answer.concat():que.que_answer;
                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                    que.editing = false;
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
            },
            chagePaperStatus: function() {
                if (!this.ques.length && this.paper.qus_status === 0) {
                    this.notice = {type: 0, msg: '请先添加题目'};
                }
                this.$http.post('/questionSet/changeStatus', {qus_id: this.paper.qus_id}).then(function(resp) {
                    if (resp.data.status === 1) {
                        this.notice = {type: 1, msg: resp.data.message};
                        this.paper.qus_status = this.paper.qus_status == 2 || this.paper.qus_status == 0 ? 1 : 2;
                    } else {
                        this.notice = {type: 0, msg: resp.data.message};
                    }
                }, function(resp) {
                    // error callback
                    this.notice = {type: 0, msg: resp.statusText};
                })
            }
        }
    }
</script>

<style>
#question-container .row {
    margin-top: 20px;
}

.quiz-name, .stu-name{
    font-size: 18px;
    margin-right: 10px;
}

#scrollspy .affix {
    top: 10px;
}

#question-container a {
    /*color: #818181;*/
}

#question-container a:hover {
    text-decoration: none;
    opacity: 0.8;
}

#question-container a:focus {
    text-decoration: none;
}

ul.nav-tabs {
    background-color: #fff;
    border: 1px solid #ecf0f1;
}

ul.affix-top,
ul.affix {
    width: 160px;
}

ul.nav-tabs .btn {
    width: 100%;
    color: #000;
    padding: 16px 0;
    border-top: 1px solid #f2f2f2;
}

ul.nav-tabs .btn-link:hover {
    text-decoration: none;
}

ul.nav-tabs .btn-link:focus {
    outline: 0;
}

ul.nav-tabs li:hover {
    box-shadow: 0 0 1px #868686;
}

ul.nav-tabs li:first-child {
    padding: 14px 0;
    font-size: 16px;
    text-align: center;
    background-color: #f5f5f5;
}

.nav-stacked>li+li {
    margin-top: 0;
}

.container {
    margin-bottom: 100px;
}

.edit-panel, .display-panel {
    border-color: #ecf0f1;
    border-width: 1px;
    border-radius: 0;
}

.display-panel {
    border-width: 1px 1px 0px 1px;
}

.sortable-list li:last-child .display-panel {
    border-width: 1px;
}

.sortable-list li:first-child .edit-panel {
    margin-top: 0;
} 

.panel .box-title .que-score {
    width: 40px;
    height: 25px;
    margin-right: 30px;
}

.panel .box-title .que-title{
    margin-right: 20px;
}

.edit-panel .panel-body,
.display-panel .panel-body {
    padding: 0 30px 20px;
}

.display-panel .box-body,
.edit-panel .box-body {
    margin-top: 10px;
}

.edit-panel .panel-footer {
    padding: 15px 20px; 
}

.edit-panel .panel-footer .btn{
    margin-right: 10px;
}

.edit-btn-group a{
    margin-left: 5px;
}

.edit-btn-group {
    display: block;
}

.panel:hover {
    box-shadow: 0 0 4px #c6c6c6;
}

.edit-panel .box-body p,
.display-panel .box-body p {
    font-size: 16px;
    margin-top: 15px;
    margin-bottom: 15px;
}

.display-panel .edit-btn-group {
    display: none;
}

.display-panel:hover .edit-btn-group {
    display: block;
}

.edit-panel {
    box-shadow: 0 0 4px #c6c6c6;
    margin-top: 15px;
    margin-bottom: 15px;
}

.display-panel {
    margin-bottom: 1px;
}

.que-content {
    width: 100%;
    font-size: 16px;
}

.que-area {
    border: 2px solid #fff;
}

.que-area:hover {
    border-bottom: 2px solid #aaa;
}

.que-area:focus{
    border-bottom: 2px solid #3498db;
    outline: 0;
}

.que-area-static {
    border: 1px solid #fff;
    border-bottom: 1px solid #c8c8c8;
}

.que-area-static:focus {
    outline: 0;
    border-bottom: 1px solid #c8c8c8;
}

.que-item {
    display: inline-block;
    vertical-align: middle;
    width: 90%;
}

.que-item + .note-editor {
    display: inline-block;
    width: 88%;
    border: 1px solid #ecf0f1;
    vertical-align: top;
    padding: 2px 8px;
}

.display-item {
    display: inline-block;
    width: 88%;
    vertical-align: top;
}

.radio, .checkbox {
    margin-bottom: 18px;
}

.edit-panel .radio {
    position: relative;
}

.edit-panel .radio>label,
.display-panel .radio>label,
.edit-panel .checkbox>label,
.display-panel .checkbox>label {
    width: 7%;
}

a.del-item {
    display: none;
    position: absolute;
    top: 2px;
    right: 0;
}

.radio:hover a.del-item,
.checkbox:hover a.del-item {
    display: block;
}

.is_cor {
    position: absolute;
    top: 24px;
    left: 25px;
}

.box-title {
    padding-top: 20px;
}

.box-title .glyphicon-ok {
    color: #27ae60;
}

.box-title .glyphicon-remove {
    color: #c0392b;
}

.page-title {
    margin-top: 10px;
    margin-bottom: 25px;
}

.stu-score {
    font-size: 16px;
}

.que-judge 

.nav-result li {
    margin-left: 20px;
    font-size: 16px;
}

.sortable-ghost {
    opacity: .5
}

ul.sortable-list {
    margin: 0;
    padding: 0;
    list-style: none
}

ul.sortable-list li {
    display: block;
}

.handle {
    cursor: move;
}

/* 隐藏summernote的resizebar */
.note-resizebar {
    display: none;
}
.note-editor.note-frame {
    border: 1px solid #ecf0f1;
}
</style>